package com.zhugang.week10;

/**
 * @program algorithms
 * @description: minPathSum
 * @author: chanzhugang
 * @create: 2022/08/29 18:01
 */
public class MinPathSum {

    /**
     * 64 最小路径和
     *
     * @param grid
     * @return
     */
    public int minPathSum(int[][] grid) {
        // 二维网格，从左上角到右下角路径，求路径和最小，每次只能向下或者向右
        // 到达(i, j)这个位置的最短路径
        // dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m][n];

        // 初始化第一行和第一列
        int len = 0;
        for (int i = 0; i < m; i++) {
            len += grid[i][0];
            dp[i][0] = len;
        }
        len = 0;
        for (int j = 0; j < n; j++) {
            len += grid[0][j];
            dp[0][j] = len;
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                // 状态转移方程
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }
        return dp[m - 1][n - 1];
    }
}